// fileop.c

#include <stdio.h>
#include <string.h>
#include "fileops.h"

#define FILENAME "data.txt"

void writePatientToFile(Patient p) {
    FILE *file = fopen(FILENAME, "a");
    if (file) {
        fprintf(file, "%s,%d,%s,%s,%s\n", p.name, p.age, p.gender, p.disease, p.admissionDate);
        fclose(file);
    }
}

void readAllPatientsFromFile(Patient patients[], int *count) {
    FILE *file = fopen(FILENAME, "r");
    *count = 0;
    if (file) {
        while (fscanf(file, "%[^,],%d,%[^,],%[^,],%[^\n]\n", patients[*count].name, &patients[*count].age,
                      patients[*count].gender, patients[*count].disease, patients[*count].admissionDate) != EOF) {
            (*count)++;
        }
        fclose(file);
    }
}

void deletePatientFromFile(const char* name) {
    FILE *file = fopen(FILENAME, "r");
    FILE *tempFile = fopen("temp.txt", "w");  // 创建一个临时文件存储未被删除的病人信息
    Patient p;

    if (file && tempFile) {
        while (fscanf(file, "%[^,],%d,%[^,],%[^,],%[^\n]\n", p.name, &p.age, p.gender, p.disease, p.admissionDate) != EOF) {
            if (strcmp(name, p.name) != 0) {  // 如果病人姓名不是要删除的，写入临时文件
                fprintf(tempFile, "%s,%d,%s,%s,%s\n", p.name, p.age, p.gender, p.disease, p.admissionDate);
            }
        }
        fclose(file);
        fclose(tempFile);
        remove(FILENAME);  // 删除原文件
        rename("temp.txt", FILENAME);  // 重命名临时文件为原文件
    }
}

void modifyPatientInFile(const char* name, Patient newInfo) {
    FILE *file = fopen(FILENAME, "r");
    FILE *tempFile = fopen("temp.txt", "w");
    Patient p;

    if (file && tempFile) {
        while (fscanf(file, "%[^,],%d,%[^,],%[^,],%[^\n]\n", p.name, &p.age, p.gender, p.disease, p.admissionDate) != EOF) {
            if (strcmp(name, p.name) == 0) {  // 如果病人姓名是要修改的，写入新信息
                fprintf(tempFile, "%s,%d,%s,%s,%s\n", newInfo.name, newInfo.age, newInfo.gender, newInfo.disease, newInfo.admissionDate);
            } else {
                fprintf(tempFile, "%s,%d,%s,%s,%s\n", p.name, p.age, p.gender, p.disease, p.admissionDate);
            }
        }
        fclose(file);
        fclose(tempFile);
        remove(FILENAME);
        rename("temp.txt", FILENAME);
    }
}
